package com.martin.lib_base.utils

import android.content.Context
import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView
import dev.utils.common.ReflectUtils
import java.lang.Boolean
import java.lang.reflect.Method
import kotlin.Exception
import kotlin.String
import kotlin.apply

/**
 * @author：Houge
 * @date：2022/1/11 19:28
 */
object WebViewUtils {

    /**
     * 创建WebView
     */
    fun createWebView(context: Context): WebView {
        val webView = WebView(context)
        //基础设置
        webView.settings.apply {
            javaScriptEnabled = true
            javaScriptCanOpenWindowsAutomatically = true
            useWideViewPort = true
            loadWithOverviewMode = true
            //支持H5标签
            domStorageEnabled = true
            //支持缩放
            setSupportZoom(true)
            //内置缩放组件
            builtInZoomControls = true
            //显示缩放组件
            displayZoomControls = true

            cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
            //允许文件访问
            allowFileAccess = true

            //启用定位
            setGeolocationEnabled(true)

            //处理http和https混合的问题
            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

            // 允许javascript出错
            ReflectUtils.reflect(WebView::class.java)
                .method("setWebContentsDebuggingEnabled", true)

            CookieManager.getInstance().apply {
                setAcceptCookie(true)
                setAcceptThirdPartyCookies(webView, true)
            }

            //自动加载图片
            loadsImagesAutomatically = true
            //编码格式
            defaultTextEncodingName = "utf-8"
        }
        return webView
    }

    /**
     * 获取Html模板
     * 用于富文本加载功能
     */
    fun getHtmlData(bodyHTML: String): String {
        val head = ("<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:100%; height:auto;}*{margin:0px;}</style>"
                + "</head>")

        return "<html>$head<body>$bodyHTML</body></html>"
    }


}